package com.zjx.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

@Configuration
@EnableConfigurationProperties(CorsProperties.class)
public class CorsConfig {

    @Autowired
    private CorsProperties corsProperties;

    // 配置跨域过滤器
    @Bean
    public CorsFilter corsFilter() {
        CorsConfiguration configuration = new CorsConfiguration();
        // 配置中的跨域域名 是存放在 CorsConfiguration
        // CorsConfiguration -> UrlBasedCorsConfigurationSource -> CorsFilter
        for (String allowOrigin : corsProperties.getAllowOrigins()) {
            configuration.addAllowedOrigin(allowOrigin);
        }
        // @CrossOrigin(originPatterns = "*", allowCredentials = "true")
        // 允许携带cookie信息
        configuration.setAllowCredentials(true);
        // 允许全部的头信息
        configuration.addAllowedHeader("*");
        // 允许全部请求方式
        configuration.addAllowedMethod("*");

        UrlBasedCorsConfigurationSource configurationSource = new UrlBasedCorsConfigurationSource();
        configurationSource.registerCorsConfiguration("/**", configuration);
//        CorsConfigurationSource -> UrlBasedCorsConfigurationSource是实现类
        return new CorsFilter(configurationSource);
    }
}